package com.lqk.channel.socket.serversocketchannel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * 可以将 ServerSocketChannel 理解为服务端。
 */
public class ServerSocketChannelDemo {
    public static void main(String[] args) throws Exception {
        //端口号
        int port = 8888;
        //创建buffer
        ByteBuffer buffer= ByteBuffer.wrap("hello lqk".getBytes());
        //创建ServerSocketChannel
        ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
        //绑定
        serverSocketChannel.socket().bind(new InetSocketAddress(port));
        //设置非阻塞模式
        serverSocketChannel.configureBlocking(false);

        //一直监听是否有新的连接传入
        while (true){
            System.out.println("waiting for connections");
            //创建SocketChannel，可以在非阻塞模式下运行
            SocketChannel sc = serverSocketChannel.accept();
            if (sc==null){
                System.out.println("没有新的连接传入：null");
                Thread.sleep(2000);
            }else {
                System.out.println("Incoming connection from: "+sc.socket().getRemoteSocketAddress());
                buffer.rewind();//表示指针指向0，要开始操作了，将position设为0，可以重读buffer中的数据
                sc.write(buffer);
                sc.close();
            }
        }

    }
}
